package com.jd.threed.生产者消费者原理;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

public class Producer implements Runnable{

    public volatile boolean canceled = false;

    BlockingQueue<Integer> stroge;


    public Producer (BlockingQueue stroge) {
        this.stroge = stroge;
    }


    @Override
    public void run() {
        int num = 0;

        try {
            while (num <100000 && !canceled) {
                if (num % 50 == 0) {
                    stroge.put(num);
                    System.out.println("入队"+num);
                }
                num++;
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            System.out.println("生产结束");
        }

    }


    public static void main(String[] args) throws InterruptedException {
        ArrayBlockingQueue<Integer> storge = new ArrayBlockingQueue<>(8);

        Producer producer = new Producer(storge);

        Thread thread = new Thread(producer);


        thread.start();

        Thread.sleep(500);


        Consumer consumer = new Consumer(storge);

        while (consumer.nededMoreNums()) {
            System.out.println(consumer.storage.take()+"被消费了");
            Thread.sleep(100);
        }

        System.out.println("消费者不需要更多的数据了");

        producer.canceled = true;

        System.out.println("标志位"+producer.canceled);

    }
}
